import router from "@/router";
import setting from "./setting";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });
import useUserStore from "./store/modules/user";
import pinia from "./store";
const userStore = useUserStore(pinia);

router.beforeEach(async (to: any, from: any, next: any) => {
  console.log(to,from);
  
  document.title = `${setting.title} - ${to.meta.title}`;
  nprogress.start();
  const token = userStore.token;
  if (token) {
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      if (userStore.username) {
        next();
      } else {
        try {
          // 获取用户信息
          await userStore.userGetInfo();
          next({ ...to, replace: true });
        } catch (err) {
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
router.afterEach((to: any, from: any) => {
  nprogress.done();
});
